<template>
  <div class="h-full bg-slate-50 p-6 overflow-y-auto">

    <!-- 1. 页面主标题区域 -->
    <div class="text-center mb-6 p-6 bg-white rounded-lg shadow-sm">
      <h2 class="flex items-center justify-center gap-3 text-2xl font-semibold text-gray-800 mb-2">
        <n-icon class="text-3xl text-blue-500" :component="CalendarEditIcon" />
        <span>{{ pageTitle }}</span>
      </h2>
      <p class="text-gray-500">请在此处填写活动的详细信息</p>
    </div>

    <!-- 2. 重要提示信息区域 -->
    <div class="mb-6 bg-blue-50 border border-blue-200 rounded-lg p-4">
      <div class="flex items-center gap-3 mb-3">
        <n-icon class="text-xl text-blue-600" :component="InfoIcon" />
        <h3 class="text-md font-semibold text-blue-800">填写提示</h3>
      </div>
      <div class="space-y-2 text-sm text-blue-700">
        <p>• 一个有意义的“活动名称”能够帮助成员快速了解活动主题。</p>
        <p>• “活动类型”有助于后续进行分类统计和归档。</p>
        <p>• “参与人员”名单对于记录党员参与度至关重要。</p>
      </div>
    </div>

    <!-- 3. 表单卡片区域 -->
    <n-card class="rounded-lg shadow-sm" :bordered="false">
       <template #header>
        <div class="flex items-center gap-3">
          <n-icon class="text-xl text-blue-500" :component="FormIcon" />
          <span class="text-lg font-semibold text-gray-800">活动详情表单</span>
        </div>
      </template>

      <n-form ref="formRef" :model="formValue" :rules="rules" label-placement="top">
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="活动名称" path="activityName">
            <n-input v-model:value="formValue.activityName" placeholder="例如：学习党的二十大精神主题党日" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="活动日期" path="activityDate">
            <n-date-picker
              v-model:formatted-value="formValue.activityDate"
              type="date"
              value-format="yyyy-MM-dd"
              class="w-full"
              @update:value="handleDateChange"
            />
          </n-form-item-gi>
          <n-form-item-gi :span="24" label="活动类型" path="activityType">
             <n-select
              v-model:value="formValue.activityType"
              :options="activityTypeOptions"
              placeholder="请选择活动类型"
            />
          </n-form-item-gi>
          <n-form-item-gi :span="24" label="活动内容摘要" path="activityContent">
            <n-input
              v-model:value="formValue.activityContent"
              type="textarea"
              :rows="4"
              placeholder="简要描述活动的主要内容、流程和意义..."
            />
          </n-form-item-gi>
          <n-form-item-gi :span="24" label="参与人员" path="participants">
            <div class="space-y-3">
              <n-card size="small" :bordered="false" class="bg-gray-50">
                <div class="flex items-center justify-between mb-2">
                  <span class="text-sm text-gray-600">从党支部党员中选择参与人员</span>
                  <div class="flex items-center gap-2">
                    <n-input
                      v-model:value="memberSearchKeyword"
                      placeholder="搜索党员姓名或学号"
                      clearable
                      size="small"
                      style="width: 200px"
                    >
                      <template #prefix><n-icon :component="SearchIcon" /></template>
                    </n-input>
                    <n-button size="tiny" @click="refreshEligibleMembers">
                      <template #icon><n-icon><refresh-outline /></n-icon></template>
                      刷新
                    </n-button>
                  </div>
                </div>
                
                <n-data-table
                  :columns="memberColumns"
                  :data="filteredEligibleMembers"
                  :pagination="{ pageSize: 5 }"
                  :row-key="row => row.memberId"
                  v-model:checked-row-keys="selectedParticipantIds"
                  size="small"
                  max-height="200px"
                  class="mb-3"
                />
                
                <div class="flex items-center justify-between">
                  <span class="text-sm text-gray-500">已选择 {{ selectedParticipantIds.length }} 人</span>
                  <n-button size="small" type="primary" @click="addSelectedParticipants">
                    添加选中人员
                  </n-button>
                </div>
              </n-card>
              <n-divider style="margin: 12px 0;" />
              <n-dynamic-tags v-model:value="formValue.participants" @create="onCreateParticipant" />
            </div>
          </n-form-item-gi>
        </n-grid>
      </n-form>
    </n-card>

  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, h } from 'vue';
import {
  NForm, NFormItem, NFormItemGi, NInput, NSelect, NDatePicker,
  NCard, NGrid, NIcon, NDynamicTags, NCheckboxGroup, NCheckbox,
  NSpace, NDivider, NButton, NScrollbar, NTag, NTooltip, NDataTable
} from 'naive-ui';
import {
  CreateOutline as FormIcon,
  InformationCircleOutline as InfoIcon,
  CalendarOutline as CalendarEditIcon,
  RefreshOutline,
  SearchOutline,
  PersonOutline
} from '@vicons/ionicons5';

const props = defineProps({
  mode: { type: String, required: true, default: 'edit' }, // 'add', 'edit'
  initialData: { type: Object, default: null },
  branchData: { type: Object, default: null }
});

const formRef = ref(null);

// --- 动态标题 ---
const pageTitle = computed(() => {
  return props.mode === 'add' ? '新增活动记录' : '编辑活动记录';
});

// --- 表单数据模型 ---
const formValue = ref({
  activityName: '',
  activityDate: null,
  activityType: null,
  activityContent: '',
  participants: []
});

// --- 参与人员选择相关 ---
const eligibleMembers = ref([]);
const selectedParticipantIds = ref([]);
const memberSearchKeyword = ref('');

// 搜索过滤后的党员列表
const filteredEligibleMembers = computed(() => {
  if (!memberSearchKeyword.value) {
    return eligibleMembers.value;
  }
  
  const keyword = memberSearchKeyword.value.toLowerCase();
  return eligibleMembers.value.filter(member =>
    member.memberName.toLowerCase().includes(keyword) ||
    member.studentId.toLowerCase().includes(keyword)
  );
});

// 党员表格列定义
const memberColumns = [
  { type: 'selection' },
  {
    title: '姓名',
    key: 'memberName',
    render: (row) => h('div', { class: 'flex items-center gap-2' }, [
      h(NIcon, { component: PersonOutline, class: 'text-gray-500' }),
      h('span', row.memberName)
    ])
  },
  {
    title: '学号',
    key: 'studentId'
  },
  {
    title: '政治面貌',
    key: 'politicalStatus',
    render: (row) => h(NTag, {
      type: row.politicalStatus === '正式党员' ? 'success' : 'warning',
      size: 'small'
    }, { default: () => row.politicalStatus })
  },
  {
    title: '班级',
    key: 'class'
  },
  {
    title: '联系方式',
    key: 'phoneNumber'
  }
];

// --- 表单规则 ---
const rules = {
  activityName: { required: true, message: '请输入活动名称', trigger: 'blur' },
  activityDate: { required: true, message: '请选择活动日期', trigger: 'change' },
  activityType: { required: true, message: '请选择活动类型', trigger: 'change' }
};

// --- 活动类型选项 ---
const activityTypeOptions = [
  { label: '主题党日', value: '主题党日' },
  { label: '组织生活会', value: '组织生活会' },
  { label: '志愿服务', value: '志愿服务' },
  { label: '理论学习', value: '理论学习' },
  { label: '其他', value: '其他' },
];

// --- 计算符合条件的党员 ---
const computeEligibleMembers = () => {
  if (!props.branchData || !props.branchData.currentMembers || !formValue.value.activityDate) {
    eligibleMembers.value = [];
    return;
  }
  
  // 获取活动日期
  const activityDate = new Date(formValue.value.activityDate);
  
  // 获取当前党支部的所有党员
  const members = props.branchData.currentMembers;
  
  // 过滤出在活动日期时属于该党支部的未毕业预备党员和正式党员
  const eligible = members.filter(member => {
    // 检查政治面貌
    const politicalStatus = member.politicalStatus;
    const isEligibleByStatus = politicalStatus === '预备党员' || politicalStatus === '正式党员';
    
    // 检查学籍状态
    const enrollmentStatus = member.enrollmentStatus;
    const isNotGraduated = enrollmentStatus !== '已毕业' && enrollmentStatus !== '毕业';
    
    // 检查在活动日期时是否属于该党支部
    if (!member.joinDate) return false;
    const joinDate = new Date(member.joinDate);
    const leaveDate = member.leaveDate ? new Date(member.leaveDate) : null;
    
    const belongsToBranchOnActivityDate = joinDate <= activityDate &&
      (!leaveDate || leaveDate >= activityDate);
    
    return isEligibleByStatus && isNotGraduated && belongsToBranchOnActivityDate;
  });
  
  eligibleMembers.value = eligible;
};

// --- 日期变化处理 ---
const handleDateChange = () => {
  computeEligibleMembers();
  // 清空已选择的参与人员
  selectedParticipantIds.value = [];
};

// --- 刷新符合条件的党员 ---
const refreshEligibleMembers = () => {
  computeEligibleMembers();
};

// --- 添加选中的参与人员 ---
const addSelectedParticipants = () => {
  selectedParticipantIds.value.forEach(memberId => {
    const member = eligibleMembers.value.find(m => m.memberId === memberId);
    if (member && !formValue.value.participants.includes(member.memberName)) {
      formValue.value.participants.push(member.memberName);
    }
  });
  // 清空已选择的项目
  selectedParticipantIds.value = [];
};

// --- 创建参与人员标签 ---
const onCreateParticipant = (value) => {
  return value;
};

// --- 初始化表单数据 ---
onMounted(() => {
  if (props.mode === 'edit' && props.initialData) {
    // 使用 initialData 初始化表单
    formValue.value = { ...props.initialData };
  } else {
    // 新增模式，设置默认日期为今天
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    formValue.value.activityDate = `${year}-${month}-${day}`;
  }
  
  // 计算符合条件的党员
  computeEligibleMembers();
});

// --- 监听 branchData 变化 ---
watch(() => props.branchData, () => {
  computeEligibleMembers();
}, { deep: true });

// --- 暴露给父组件的方法 ---
const validateAndGetData = async () => {
  try {
    await formRef.value?.validate();
    return { mode: props.mode, data: formValue.value };
  } catch (errors) {
    console.warn("表单验证失败:", errors);
    return null;
  }
};

defineExpose({ validateAndGetData });
</script>
